package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.UserBehavior;
import com.atguigu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

public class Flink03_Project_High_UV {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .readTextFile("input/UserBehavior.csv")
                .map(line -> {
                    String[] data = line.split(",");
                    return new UserBehavior(
                            Long.valueOf(data[0]),
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2]),
                            data[3],
                            Long.parseLong(data[4]) * 1000);
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
                )
                .filter(ub -> "pv".equals(ub.getBehavior()))
                .keyBy(UserBehavior::getBehavior)
                .window(TumblingEventTimeWindows.of(Time.minutes(30)))
                .process(
                        new ProcessWindowFunction<UserBehavior, String, String, TimeWindow>() {

                            private MapState<Long, Object> userIdState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                userIdState = getRuntimeContext().getMapState(
                                        new MapStateDescriptor<Long, Object>(
                                                "userIdState",
                                                Long.class,
                                                Object.class
                                        ));
                            }

                            @Override
                            public void process(String key, Context ctx, Iterable<UserBehavior> elements, Collector<String> out) throws Exception {
                                userIdState.clear();
                                for (UserBehavior ub : elements) {
                                    userIdState.put(ub.getUserId(), new Object());
                                }
                                List<Long> uids = AtguiguUtil.toList(userIdState.keys());
                                out.collect(ctx.window() + " " + uids.size());

                            }
                        })
                        .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
